#This version of GApi(3) use the GoogleApi as listed in https://developers.google.com/maps/documentation/directions/
#using database and tastypie
#abit redundant?

from GApiv3.models import PublicTrans
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import urllib
from urllib import urlopen
import json
import datetime
import time

DIRECTION_BASE_URL = 'http://maps.googleapis.com/maps/api/directions/json'

# get current time and convert to epoch
def getCurrentTime():
    t = datetime.datetime.now()
    return int(time.mktime(t.timetuple()))

# get the location form request,this is just for php form testing
def getLocation(request):
    if request.POST.get('origin'):
        origin = request.POST.get('origin')
        destination = request.POST.get('destination')
    else:
        origin_lat = request.POST.get('origin_lat')
        origin_lng = request.POST.get('origin_lng')
        destination_lat = request.POST.get('destination_lat')
        destination_lng = request.POST.get('destination_lng')
        origin = origin_lat + ',' + origin_lng
        destination = destination_lat + ',' + destination_lng
    return origin, destination

# generate GoogleMapsApi url
def genUrl(origin, destination, mode, time, **DirArgs):
    DirArgs.update({
        'origin': origin,
        'destination': destination,
        'mode': mode,
        'departure_time': time,
        'sensor': 'false',
        })
    url = DIRECTION_BASE_URL + '?' + 'region=sg&'+urllib.urlencode(DirArgs)
    return url

# update Database
def genDatabase(Response, phone, origin, destination):
    allStep = []
    i = 1
    for route in Response['routes']:
        for leg in route['legs']:
            distance = leg['distance']['text']
            duration = leg['duration']['text']
            j = 1
            for step in leg['steps']:
                thisStep = step['html_instructions'].decode('unicode-escape')
                allStep.append(str(j)+'. '+thisStep)
                j += 1
            direction = allStep
            postDb = PublicTrans(phone= phone, distance=distance, direction=direction, duration=duration,
                origin=origin, destination=destination)
            postDb.save()

            i +=1
    return None

# the main view
@csrf_exempt
def main3(request):

    origin = ''
    destination = ''
    mode = 'transit'
    time = getCurrentTime()
    phone = ''

    if request.method == 'POST':
        phone = request.POST.get('phone')
        origin, destination = getLocation(request)

    url = genUrl(origin, destination, mode, time)
    jsonResponse = json.load(urlopen(url))

    status_code = jsonResponse['status']

    if status_code != "OK":
        return HttpResponse("Fail. Jiayou") #should change to raise some error
    else:
        #update response in database
        genDatabase(jsonResponse, phone, origin, destination)

        return HttpResponseRedirect('http://127.0.0.1:8000/api/pt3/%s/?format=json' % phone)


